﻿
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.Common;
using Models.JsonResultModel;
using Models.Constant;
using ServiceWeb.DBGateway;
using ServiceWeb.WebClient;
using System.Reflection.Emit;
using Models.Device;
using ServiceWeb.APIRequest;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Common;

namespace GatewayServer.Controllers
{
    public class GateWayController : BaseMagerController
    {
        EFYihongIotContext ef = new EFYihongIotContext();
        public IActionResult list(IFormCollection FC, HttpReqModel httpRequest, iot_product reqProduct, int PageIndex = 1, int PageSize = 15, string type = "1")
        {
            ViewData["reqProduct"] = reqProduct;
            List<SugarParameter> sugarParameters = new List<SugarParameter>();
            int totalRecord = 0;
            string sqlwhere = "  ";
            if (!string.IsNullOrEmpty(httpRequest.name))
            {
                sqlwhere = sqlwhere + " and d_name like CONCAT('%',@name,'%') ";
                sugarParameters.Add(new SugarParameter("name", httpRequest.name));
            }
            if (!string.IsNullOrEmpty(FC["hid_pageIndex"]))
            {
                PageIndex = int.Parse(FC["hid_pageIndex"].ToString());

            }
            if (!string.IsNullOrEmpty(reqProduct.p_guid))
            {
                sqlwhere = sqlwhere + "  and d_p_guid = @d_p_guid ";
                sugarParameters.Add(new SugarParameter("d_p_guid", reqProduct.p_guid));

            }
            if (!string.IsNullOrEmpty(httpRequest.status))
            {
                //设置状态
                sqlwhere = sqlwhere + " and d_status=@status";
                sugarParameters.Add(new SugarParameter("status", httpRequest.status));
            }
            string sql = "select  w.*,a.*,(case when ls_id is not null then '在线' else '离线' end) live from iot_device_gateway w inner join iot_device a  on gw_d_guid=d_guid inner join iot_device_model on d_model_guid =m_guid  left join iot_device_live_state ls on ls_d_guid=d_guid and ls_live_state_set_time>DATE_ADD(now(),INTERVAL -1 MINUTE)  where m_attribute=3   " + sqlwhere;
            DataTable dt = MySqlYihongIot.getPageDataTable(PageIndex, PageSize, sql, sugarParameters, "d_id desc", ref totalRecord);
            ViewData["DataList"] = dt;
            ViewBag.PageSize = PageSize;
            ViewBag.RecordCount = totalRecord;//总条数
            ViewBag.PageCount = totalRecord % PageSize == 0 ? totalRecord / PageSize : totalRecord / PageSize + 1;//分的页数
            ViewBag.PageIndex = PageIndex;//当前页码
            return View(httpRequest);
        }

        public IActionResult edit(HttpReqModel httpReqModel, string p_guid)
        {
            ViewBag.d_p_guid = p_guid;
            if (httpReqModel.order == "upd")
            {
                ViewBag.d_guid = httpReqModel.guid.ToString();
            }
            else
            {
                ViewBag.d_guid = Guid.NewGuid().ToString();
            }
            ViewBag.order = httpReqModel.order;
            return View();
        }
        public RespResultData getModelList()
        {
            return RespResult.Sucess(new DBIotDeviceModel().getGateWayModelList());
        }

        public IActionResult upgrade(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            ViewBag.gw_system = gwmodel.gw_system;
            ViewBag.gw_software_version = gwmodel.gw_software_version;
            iot_device_software_publish spmodel = efgw.iot_device_software_publish.Where(c => c.swp_status == 0).FirstOrDefault();

            ViewBag.swp_service_name = spmodel.swp_service_name;
            ViewBag.swp_packages_url = spmodel.swp_packages_url;
            ViewBag.swp_version = spmodel.swp_version;
            return View();
        }
        public RespResultData saveUpGrade(HttpReqModel httpReqModel)
        {
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            //   new ServiceDeviceGateway().updateGradeSoftware(gwmodel.gw_guid);

            new ServiceDeviceControl().updateGradeSoftware(gwmodel.gw_code, "后台");

            return RespResult.Sucess();
        }

        public IActionResult sendCommand(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            return View();
        }

        public RespResultData saveSend(HttpReqModel httpReqModel, iot_device reqDevice)
        {
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(httpReqModel.content))
            {

                return RespResult.Sucess("");
            }

            new ServiceDeviceControl().sendbashCommand(gwmodel.gw_code, httpReqModel.content, "后台");
            Thread.Sleep(2000);
            string sql = "select * from iot_device_minimachinecommand_log  where c_gw_code='" + gwmodel.gw_code + "' order by c_id desc limit 1";
            DataTable dtResult = new MySqlYihongIot().Db.Ado.GetDataTable(sql);
            string result = "";
            if (dtResult.Rows.Count > 0)
            {
                result = dtResult.Rows[0]["c_return_msg"].ToString();
            }
            // string result = new ServiceSendMQ().sendBashCommand(httpReqModel.content, gwmodel.gw_code);
            return RespResult.Sucess(result);


        }

        public IActionResult sendCommandRestart(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            return View();
        }

        public RespResultData saveSendRestart(HttpReqModel httpReqModel, iot_device reqDevice)
        {
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();

            new ServiceDeviceControl().sendbashCommand(gwmodel.gw_code, "reboot", "后台");// new ServiceSendMQ().sendBashCommand("reboot", gwmodel.gw_code);
            return RespResult.Sucess();
        }
        public IActionResult setConfig(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            return View();
        }

        public RespResultData saveSetConfig(HttpReqModel httpReqModel, iot_device reqDevice, ModelConfigKeyValue modelConfig, string quene)
        {
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();


            new ServiceDeviceControl().upConfigAppSetting(gwmodel.gw_code, modelConfig, "后台");


            //  new ServiceCloodAPIControl_ext().upConfigAppSetting(modelConfig, quene + gwmodel.gw_code);
            return RespResult.Sucess();
        }

        public IActionResult setMQTTConfig(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            return View();
        }
        public IActionResult setWifi(HttpReqModel httpReqModel)
        {
            ViewBag.d_guid = httpReqModel.guid;
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == httpReqModel.guid).FirstOrDefault();
            ViewBag.gw_code = gwmodel.gw_code;
            return View();
        }

        //public RespResultData saveSetWifi(HttpReqModel httpReqModel, iot_device reqDevice, iot_device_gateway_wifi wifi)
        //{
        //    EFIotGatewayContext efgw = new EFIotGatewayContext();
        //    iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();
        //    wifi.wf_d_guid = reqDevice.d_guid;
        //    string result = new DBIotDeviceGatewayWifi().Add(wifi, gwmodel.gw_code);
        //    return RespResult.Sucess(result);
        //}
        public RespResultData saveSetMQTTConfig(HttpReqModel httpReqModel, iot_device reqDevice, MQTTInfo mQTTInfo, string quene)
        {
            EFYihongIotContext efgw = new EFYihongIotContext();
            iot_device_gateway gwmodel = efgw.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();

            new ServiceDeviceControl().upGradeMQTTConfig(gwmodel.gw_code, mQTTInfo, "后台");

            //  new ServiceCloodAPIControl_ext().upGradeMQTTConfig(mQTTInfo, quene + gwmodel.gw_code);
            return RespResult.Sucess();
        }

        public RespResultData changeStatus(HttpReqModel httpReqModel)
        {
            new DBIotDevice().changeStatus(httpReqModel.guid);
            return RespResult.Sucess();
        }

        public RespResultData saveGateWay(IFormCollection FC, HttpReqModel httpRequest, iot_device req, iot_device_gateway gateway)
        {

            new DBIotDevice().saveGateWay(LoginUserInfo, req, gateway);
            return RespResult.Sucess();
        }
        public RespResultData getDevice(HttpReqModel httpRequest)
        {
            return RespResult.Sucess(new DBIotDevice().getDevice(httpRequest.guid));
        }

        public RespResultData getGateWay(HttpReqModel httpRequest)
        {
            return RespResult.Sucess(new DBIotDeviceGateway().getGateway(httpRequest.guid));
        }
    }
}